//
//  ToBeSureTaskListViewController.m
//  MyProject
//
//  Created by Pei on 16/7/14.
//  Copyright © 2016年 Xiaobo Pei. All rights reserved.
//

#import "ToBeSureTaskListViewController.h"
#import "IHRefreshTableView.h"
#import "TaskManagerCell.h"
#import "CreateTaskViewController.h"
#import "NSMutableArray+Additions.h"
#import "UserInfo.h"
#import "SelectModel.h"
#import "ToBeSureTaskViewController.h"
#import "HTHorizontalSelectionList.h"
#import "ToBeSurePeiTongCell.h"
#import "ToBeSurePeiTongDetailViewController.h"

@interface ToBeSureTaskListViewController ()<UITableViewDataSource,UITableViewDelegate,IHTableViewRefreshingDelegate, ToBeSureTaskViewControllerDelegate,HTHorizontalSelectionListDelegate,HTHorizontalSelectionListDataSource, ToBeSurePeiTongDetailViewControllerDelegate>
{
    MySceneType _type;
    
    IHRefreshTableView *_myTable;
    
    UIView *_addView;
    
    UIControl *_addControl;
    
    UIButton *_rightBtn;
    
    NSArray *_contentArray;
    
    NSDictionary *_currentDic;
    
    NSString *_currentAction;
    
    HTHorizontalSelectionList *_segementView;
    
    NSArray *_titleArray;
    
    IHRefreshTableView *_secondTable;
    
    NSArray *_secondArray;
    NSDictionary *_secondDic;
}

@end

@implementation ToBeSureTaskListViewController

- (id)initWith:(MySceneType)type
{
    self = [super init];
    if (self)
    {
        _type = type;
    }
    return self;
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    
    [self.navigationController setNavigationBarHidden:NO animated:animated];
    [[NSNotificationCenter defaultCenter] postNotificationName:Hide_TabBar_Notification object:nil];
    
    //_contentArray = (NSArray*)[[NSUserDefaults standardUserDefaults] objectForKey:Create_Task];
    //[_myTable reloadData];
}

- (void)getSecondData{
    //Get_AccompanyInspectionList
    [[YMNetLib getInstance] connectWithAction:Get_AccompanyInspectionList method:@"GET" withContent:@"" withBody:nil withDelegate:self];
    _currentAction = Get_AccompanyInspectionList;
}

- (void)getData
{
    [[YMNetLib getInstance] connectWithAction:Get_ToBeSure_Task_List method:@"GET" withContent:@"" withBody:nil withDelegate:self];
    _currentAction = Get_ToBeSure_Task_List;
}

- (void)NetDoOverSuccess:(NSDictionary*)body
{
    if ([_currentAction isEqualToString:Get_ToBeSure_Task_List]) {
        if ([[YMNetDataUtil getSuccessState:body] intValue] == 1)
        {
            _currentDic = body;
            
            _contentArray = [_currentDic valueForKey:@"InspectionList"];
            [_myTable reloadData];
            
            NSArray *tempArray = [[NSUserDefaults standardUserDefaults] objectForKey:Check_Type_Items];
            if (tempArray != nil && tempArray.count > 0) {
            }else{
                [self getLevelData];
            }
        }
    }else if ([_currentAction isEqualToString:Get_AccompanyInspectionList]){
        if ([[YMNetDataUtil getSuccessState:body] intValue] == 1){
            _secondDic = body;
            _secondArray = [body objectForKey:@"List"];
            [_secondTable reloadData];
        }
        
    }else if ([_currentAction isEqualToString:Sure_ConfirmAccompany]){
        if ([[YMNetDataUtil getSuccessState:body] intValue] == 1){
            [self getSecondData];
        }
    }
    else{
        if ([[YMNetDataUtil getSuccessState:body] intValue] == 1)
        {
            [[NSUserDefaults standardUserDefaults] setObject:[body valueForKey:@"DicList"] forKey:Check_Type_Items];
            [_myTable reloadData];
        }
    }
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    _titleArray = @[@"待确认任务",@"待确认陪同检查"];
    
    [self initSelectView];
    
    
    [self initTableView];
    [self initSecondTableView];
    
    
    
    [self getData];
}

- (void)initSelectView{
    _segementView = [[HTHorizontalSelectionList alloc] initWithFrame:CGRectMake(0.0f, 0.0f, kDeviceWidth, 40.0f)];
    _segementView.delegate = self;
    _segementView.dataSource = self;
    _segementView.autoFillWidth = YES;
    _segementView.font = 14;
    _segementView.sideMargin = 0;
    _segementView.isAdjustBottomLine = YES;
    _segementView.bottomLineMargin = 10.f;
    _segementView.selectionIndicatorColor = kBlueColor;
    [_segementView setSelectedButtonIndex:0];
    [_segementView setTitleColor:kGreenColor forState:UIControlStateNormal];
    [_segementView setBottomTrimColor:kGreenColor];
    [self.view addSubview:_segementView];
}





- (void)getLevelData
{
    [[YMNetLib getInstance] connectWithAction:Dictionary_Type_API method:@"GET" withContent:@"DicType=InspectType" withBody:nil withDelegate:self];
    _currentAction = Dictionary_Type_API;
}


#pragma mark **************************** UI *********************************
- (void)initTableView
{
    CGRect frame = CGRectMake(0, _segementView.bottom, kDeviceWidth, kDeviceHeight-NAV_HEIGHT-_segementView.height);
    _myTable = [[IHRefreshTableView alloc] initWithFrame:frame refreshType:-1 andAutoLoad:NO];
    _myTable.delegate = self;
    _myTable.dataSource = self;
    _myTable.refreshDelegate = self;
    _myTable.footer.hidden = YES;
    _myTable.header.hidden = YES;
    _myTable.allowsSelectionDuringEditing = YES;
    _myTable.tag = 116;
    [self.view addSubview:_myTable];
}

- (void)initSecondTableView
{
    CGRect frame = CGRectMake(0, _segementView.bottom, kDeviceWidth, kDeviceHeight-NAV_HEIGHT-_segementView.height);
    _secondTable = [[IHRefreshTableView alloc] initWithFrame:frame refreshType:-1 andAutoLoad:NO];
    _secondTable.delegate = self;
    _secondTable.dataSource = self;
    _secondTable.refreshDelegate = self;
    _secondTable.footer.hidden = YES;
    _secondTable.header.hidden = YES;
    _secondTable.allowsSelectionDuringEditing = YES;
    _secondTable.tag = 119;
    [self.view addSubview:_myTable];
}


#pragma mark ************************** Action ************************
- (void)rightBtnAcion
{
    [_myTable setEditing:!_myTable.editing animated:YES];
    
    _addControl.hidden = YES;
    _addView.hidden = NO;
    
    [self.navigationItem setRightBarButtonItem:nil];
}

- (void)addControlAction
{
    CreateTaskViewController *createTaskVC = [[CreateTaskViewController alloc] init];
    [self.navigationController pushViewController:createTaskVC animated:YES];
}





- (void)uploadTask:(NSDictionary*)tempD
{
    NSMutableArray *InspectTaskListArray = [[NSMutableArray alloc] initWithCapacity:3];
    NSArray *tempA = [tempD objectForKey:@"InspectionItems"];
    for (NSDictionary *tempD in tempA) {
        NSMutableDictionary *dic = [[NSMutableDictionary alloc] initWithCapacity:3];
        [dic setValue:[tempD valueForKey:@"InspectContentID"] forKey:@"InspectItemCode"];
        [dic setValue:[tempD valueForKey:@"InspectContentName"] forKey:@"InspectTaskName"];
        [dic setValue:@"" forKey:@"DeadLineDate"];
        [InspectTaskListArray addObject:dic];
    }
    
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSDate *date = [dateFormatter dateFromString:[tempD valueForKey:@"InspectDate"]];
    
    //Upload_Task
    NSDictionary *bodyDic = [NSDictionary dictionaryWithObjectsAndKeys:
                             [[UserInfo getInstance] getUserID],@"UserID",//UserID
                             [tempD valueForKey:@"InspectionNo"],@"InspectionNo", //检查单号
                             [NSNumber numberWithInt:[[[tempD objectForKey:@"InspectType"] valueForKey:@"Value"] intValue]], @"InspectType", //检查类型 int  {Code = "SQCP_Security_InspectionType_Daily"; Name = "\U65e5\U5e38\U68c0\U67e5"; Value = 0;},
                             //{"projectCode":"XM201611","orgCode":"YFZX","orgName":"公司本部","unitCode":"region","unitName":"三航局","projectName":"青岛项目部"}
                             [[tempD objectForKey:@"InspectOrgAndProject"] valueForKey:@"orgCode"], @"InspectOrgCode", //被检查公司编码
                             [[tempD objectForKey:@"InspectOrgAndProject"] valueForKey:@"projectCode"], @"InspectProjectCode", //被检查项目编码
                             date, @"InspectDate", //检查时间 DateTime
                             [NSNumber numberWithInt:[[tempD valueForKey:@"InspectionState"] intValue]], @"InspectionState", //检查单状态 int
                             [tempD valueForKey:@"InspectionRemark"], @"InspectionRemark", //检查单备注
                             InspectTaskListArray,@"InspectTaskList",
                             nil];
    [[YMNetLib getInstance] connectWithAction:Upload_Task method:@"POST" withContent:nil withBody:bodyDic withDelegate:self];
    
}

//- (void)NetDoOverSuccess:(NSDictionary*)body
//{
//
//
//    NSLog(@"========error%@",[body valueForKey:@"Error"]);
//}


#pragma mark  ************************* UITableViewDataSource **************************************
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (tableView.tag == 116) {
        id tempObject = [_currentDic valueForKey:@"InspectionList"];
        if ([tempObject isKindOfClass:[NSString class]]) {
            if ([[_currentDic valueForKey:@"InspectionList"] isEqualToString:@""]) {
                return 0;
            }
        }
        return (nil == _contentArray) ? 0 : _contentArray.count;
    }else{
        id tempObject = [_secondDic valueForKey:@"List"];
        if ([tempObject isKindOfClass:[NSString class]]) {
            if ([[_secondDic valueForKey:@"List"] isEqualToString:@""]) {
                return 0;
            }
        }

        return (nil == _secondArray) ? 0 : _secondArray.count;
    }
    return 0;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (tableView.tag == 116) {
        static NSString *identifier = @"TaskManagerCell";
        TaskManagerCell *cell = (TaskManagerCell *)[tableView dequeueReusableCellWithIdentifier:identifier];
        if (cell == nil) {
            cell = [[TaskManagerCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
            
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            cell.backgroundView = [[UIView alloc] init];
        }
        NSDictionary *tempDic = [_contentArray objectAtIndex:indexPath.row];
        //cell.mSelected = [(NSNumber *)[tempDic objectForKey:@"isSelect"] boolValue];
        
        [cell showWithDataToBeSure:tempDic];
        return cell;
    }else{
       //ToBeSurePeiTongCell
        static NSString *identifier = @"ToBeSurePeiTongCell";
        ToBeSurePeiTongCell *cell2 = (ToBeSurePeiTongCell *)[tableView dequeueReusableCellWithIdentifier:identifier];
        if (cell2 == nil) {
            cell2 = [[ToBeSurePeiTongCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
            
            cell2.selectionStyle = UITableViewCellSelectionStyleNone;
            cell2.backgroundView = [[UIView alloc] init];
        }
        NSDictionary *tempDic = [_secondArray objectAtIndex:indexPath.row];
        //cell.mSelected = [(NSNumber *)[tempDic objectForKey:@"isSelect"] boolValue];
        
        [cell2 showWithData:tempDic];
        
        [cell2.passBtn addTarget:self action:@selector(passBtnAction:) forControlEvents:UIControlEventTouchUpInside];
        cell2.passBtn.tag = indexPath.row;
        
        return cell2;
    }
    return nil;
}

- (void)passBtnAction:(UIButton*)sender{
   NSDictionary *tempDic = [_secondArray objectAtIndex:sender.tag];
    
   //Sure_ConfirmAccompany
    [[YMNetLib getInstance] connectWithAction:Sure_ConfirmAccompany method:@"GET" withContent:[NSString stringWithFormat:@"AccompanyID=%d", [[tempDic valueForKey:@"AccompanyID"] intValue]] withBody:nil withDelegate:self];
    _currentAction = Sure_ConfirmAccompany;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 80;
}


-(BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    return YES;
}

- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath
{
    return NO;
}

- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)sourceIndexPath toIndexPath:(NSIndexPath *)destinationIndexPath
{
    //[_selFlags moveObjectFromIndex:sourceIndexPath.row toIndex:destinationIndexPath.row];
}


#pragma mark -
#pragma mark Table view delegate

- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return UITableViewCellEditingStyleNone;
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (tableView.tag == 116) {
        NSDictionary *tempDic = [_contentArray objectAtIndex:indexPath.row];
        
        if (tableView.isEditing)
        {
            /*
             TaskManagerCell *cell = (TaskManagerCell *)[tableView cellForRowAtIndexPath:indexPath];
             [cell changeMSelectedState];
             NSDictionary *tempDic = [_contentArray objectAtIndex:indexPath.row];
             NSMutableArray *tempArray = [[NSMutableArray alloc] initWithArray:_contentArray];
             for (int i = 0; i < tempArray.count; i++)
             {
             NSMutableDictionary *tempD = [[NSMutableDictionary alloc] initWithDictionary:[tempArray objectAtIndex:i]];
             if ([[tempDic valueForKey:@"InspectionNo"] isEqualToString:[tempD valueForKey:@"InspectionNo"]]) {
             //[NSNumber numberWithBool:YES], @"isSelect"
             //[tempD setValue:@"1" forKey:@"isSelect"];
             //[tempD removeObjectForKey:@"isSelect"];
             [tempD setObject:[NSNumber numberWithBool:cell.mSelected] forKey:@"isSelect"];
             [tempArray replaceObjectAtIndex:i withObject:tempD];
             }
             }
             _contentArray = tempArray;
             */
        }
        else
        {
            ToBeSureTaskViewController *sureVC = [[ToBeSureTaskViewController alloc] initWithDic:tempDic];
            sureVC.delegate = self;
            [self.navigationController pushViewController:sureVC animated:YES];
        }
    }else{
        NSDictionary *tempDic = [_secondArray objectAtIndex:indexPath.row];
        ToBeSurePeiTongDetailViewController *sureVC = [[ToBeSurePeiTongDetailViewController alloc] initWithDic:tempDic];
        sureVC.delegate = self;
        [self.navigationController pushViewController:sureVC animated:YES];
    }
    
}

- (void)refreshSecondData{
    [self getSecondData];
}

- (void)refreshData
{
    [self getData];
}



#pragma mark - HTHorizontalSelectionList delegate
- (NSInteger)numberOfItemsInSelectionList:(HTHorizontalSelectionList *)selectionList
{
    return _titleArray.count;
}

- (NSString *)selectionList:(HTHorizontalSelectionList *)selectionList titleForItemWithIndex:(NSInteger)index
{
    return _titleArray[index];
}

- (void)selectionList:(HTHorizontalSelectionList *)selectionList didSelectButtonWithIndex:(NSInteger)index
{
    switch (index) {
        case 0:
        {
            [_secondTable removeFromSuperview];
            
            [self.view addSubview:_myTable];
            
            [_myTable reloadData];
        }
            break;
        case 1:
        {
            [_myTable removeFromSuperview];
            [self.view addSubview:_secondTable];
            if (_secondArray != nil && _secondArray.count > 0) {
                [_secondTable reloadData];
            }else{
                [self getSecondData];
            }
            
            
        }
            break;
            
        default:
            break;
    }
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

@end
